package com.hzit.service.impl;

import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class StudentServiceImpl implements StudentService {
	private SqlSessionFactory sqlSessionFactory ;
	public StudentServiceImpl()  {
		try {
			sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//1. 查询所有学生
	@Override
	public List<Student> findAll() {
		try(SqlSession session = sqlSessionFactory.openSession()) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			return mapper.findAll();
		}
	}
	//2. 添加学生
	@Override
	public void insert(Student stud) {
		try(SqlSession session = sqlSessionFactory.openSession(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.insert(stud);
		}
	}

	//3. 根据sid查询学生
	@Override
	public Student findById(Integer sid) {
		try(SqlSession session = sqlSessionFactory.openSession(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			return mapper.findById(sid);
		}
	}
	//4. 修改学生
	@Override
	public void update(Student stud) {
		try(SqlSession session = sqlSessionFactory.openSession(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.update(stud);
		}
	}

	//5. 根据学号删除学生
	@Override
	public void deleteById(Integer sid) {
		try(SqlSession session = sqlSessionFactory.openSession(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.delete(sid);
		}
	}

}
